package vn.pyco.prez.tapestry.services.internal;
import org.apache.tapestry5.ioc.services.PerthreadManager;
import org.slf4j.Logger;

import vn.pyco.prez.tapestry.exception.TaskExceptionHandler;
import vn.pyco.prez.tapestry.services.ThreadSource;

public class ThreadSourceImpl implements ThreadSource {

    private final PerthreadManager _perthreadManager;
    private final Logger _logger;

    public ThreadSourceImpl(PerthreadManager perthreadManager, Logger logger){
        _perthreadManager = perthreadManager;
        _logger = logger;
    }
    
    /*
     * (non-Javadoc)
     * @see vn.pyco.prez.tapestry.services.ThreadSource#runInThread(java.lang.Runnable)
     */
    public void runInThread(Runnable task){
        runInThread(task,defaultTaskExceptionHandler);
    }

    /*
     * (non-Javadoc)
     * @see vn.pyco.prez.tapestry.services.ThreadSource#runInThread(java.lang.Runnable, vn.pyco.prez.tapestry.services.TaskExceptionHandler)
     */
    public void runInThread(final Runnable task, final TaskExceptionHandler taskExceptionHandler){
        new Thread(new Runnable(){

            public void run() {
                try {
                   task.run();
                } catch (Throwable e) {
                    taskExceptionHandler.exceptionThrown(task, e);
                } finally {
                    _perthreadManager.cleanup();
                }
            }
            
        }).start();
    }

    /** default exception handler that writes exception to the log */
    private final TaskExceptionHandler defaultTaskExceptionHandler = new TaskExceptionHandler(){
        public void exceptionThrown(Object task, Throwable exception) {
            _logger.error("Task failed :"+task, exception);
        }
    };
    
}